package dto.user;

import org.apache.commons.lang3.StringUtils;

import services.exception.AniDataException;

import models.*;
import models.pubobj.AniObjectState;
import models.user.*;

public class LocalUserInfoDto {

	public Long id;
	
	public String email;
	
	public String screenName;
	
	public String md5Pwd;

    public String role;
	
	public Long sessionId;

	//constructor for register
	public LocalUserInfoDto(String email, String screenName,
			String md5Pwd, String role, Long sessionId) {
		super();
		this.email = email;
		this.screenName = screenName;
		this.md5Pwd = md5Pwd;
        this.role = role;
		this.sessionId = sessionId;
	}

    //construct from DAO
    public LocalUserInfoDto(AniUser oneUser){
        super();
        this.id = oneUser.id;
        this.email = oneUser.email;
        this.screenName = oneUser.screenName;
        this.md5Pwd = oneUser.password;
        this.role = oneUser.role.roleKey;
    }
	
	//constructor for edit
	public LocalUserInfoDto(Long id, String email, String screenName,
			String md5Pwd, Long sessionId) {
		super();
		this.id = id;
		this.email = email;
		this.screenName = screenName;
		this.md5Pwd = md5Pwd;
		this.sessionId = sessionId;
	}
	
	public LocalUserInfoDto(){}

	public AniUser transToAniUserForReg(AniUserRole role, AniObjectState curState){
		return new AniUser(
				this.email,
				this.md5Pwd,
				curState,
				role,
				this.screenName
				);
	}
	
	public AniUser transToAniUserForUpdate(){
		AniUser oneUser = this.getAniUserEntity();
		if(StringUtils.isEmpty(this.md5Pwd.trim())){
			oneUser.password = this.md5Pwd;
		}
		if(StringUtils.isEmpty(this.screenName)){
			
		}
		return new AniUser(
				this.id,
				this.md5Pwd,
				this.screenName
				);
	}
	
	public AniUser getAniUserEntity(){
		AniUser oneUser = null;
		if(this.id != null && this.id > 0){
			oneUser = AniUser.find.byId(this.id);
		}else if(StringUtils.isEmpty(this.email.trim())){
			oneUser =  AniUser.findByEmail(this.email);
		}else{
			throw new AniDataException("USER_CANNOT_BE_FOUND_WITHOUT_ID_OR_EMAIL");
		}
		if(oneUser == null){
			throw new AniDataException("USER_CANNOT_BE_FOUND");
		}
		return oneUser;
	}
	
}
